#---------------------------------------------------------------------
# Helper functions.
#---------------------------------------------------------------------
function(doxygen_module_has_changed _module _modname _changed)
  set(changed TRUE)

  # check if we need to build this
  if(Subversion_FOUND AND EXISTS ${DOXYGEN_SOURCE_DIR}/${_module}/.svn)
    Subversion_WC_INFO(${DOXYGEN_SOURCE_DIR}/${_module} ${_modname})

    if(DOXYGEN_${_modname}_LAST_BUILD_REV)
      if(NOT ${_modname}_WC_LAST_CHANGED_REV GREATER ${DOXYGEN_${_modname}_LAST_BUILD_REV})
        # check whether there are uncommitted modifications
        execute_process(
          COMMAND "${Subversion_SVN_EXECUTABLE}"
            status "${DOXYGEN_SOURCE_DIR}/${_module}"
          OUTPUT_VARIABLE svn_log_output
          OUTPUT_STRIP_TRAILING_WHITESPACE
          )

        if(NOT svn_log_output)
          set(changed FALSE)
        endif()
      endif()
    endif()

    # Save the last revision built (or attempted to build).
    if(${_modname}_WC_REVISION)
      file(APPEND "${CMAKE_BINARY_DIR}/doxygen_last_build_rev.cmake"
        "set(DOXYGEN_${_modname}_LAST_BUILD_REV ${${_modname}_WC_REVISION})\n"
        )
    endif()
  endif()

  set(${_changed} ${changed} PARENT_SCOPE)
endfunction()

function(_print_header _index_html)
  set(title "VXL Documentation")
  file(READ "${DOXYGEN_SCRIPT_DIR}/doxy_header.html" index_html)
  string(CONFIGURE "${index_html}" index_html @ONLY)
  set(index_html "${index_html}
<h1>VXL Documentation</h1>
<p>C++ Libraries for Computer Vision Research and Implementation</p>
<hr />"
    )
  set(${_index_html} "${index_html}" PARENT_SCOPE)
endfunction()

function(_print_book_links _index_html)
  set(index_html "${${_index_html}}")
  foreach(book ${DOXYGEN_BOOK_LIST})
    string(REPLACE / _ bname ${book})
    set(index_html "${index_html}
<a href=\"books/${book}/book.html\">
  ${book} : ${DOXYGEN_${bname}_BOOK_DESCRIPTION}
</a>
<br />"
      )
  endforeach()
  set(${_index_html} "${index_html}" PARENT_SCOPE)
endfunction()

function(_print_library_links _index_html)
  set(index_html "${${_index_html}}")
  foreach(package ${DOXYGEN_PACKAGE_LIST})
    string(REPLACE / _ packname ${package})
    if(DOXYGEN_${packname}_LIBRARY_LIST)
      set(index_html "${index_html}
<h3>${package} : ${DOXYGEN_${packname}_DESCRIPTION}</h3>
<blockquote>"
        )
      foreach(library ${DOXYGEN_${packname}_LIBRARY_LIST})
        string(REPLACE / _ libname ${library})
        string(REGEX REPLACE ".*/" "" lib ${library})
        if(DOXYGEN_${libname}_DESCRIPTION)
          set(index_html "${index_html}
  <a href=\"${library}/html/index.html\">
    ${lib} : ${DOXYGEN_${libname}_DESCRIPTION}
  </a>
  <br />"
            )
        else()
          set(index_html "${index_html}
  <a href=\"${library}/html/index.html\">${lib}</a><br />"
            )
        endif()
      endforeach()
      set(index_html "${index_html}
</blockquote>"
        )
    endif()
  endforeach()
  set(${_index_html} "${index_html}" PARENT_SCOPE)
endfunction()

function(_print_footer _index_html)
  set(index_html "${${_index_html}}")
  execute_process(
    COMMAND ${PERL_EXECUTABLE}
      -e "$date = localtime(time()); print $date"
    OUTPUT_VARIABLE date
    OUTPUT_STRIP_TRAILING_WHITESPACE
    )
  set(index_html "${index_html}
<h2>Download</h2>
See the <a href=\"https://vxl.github.io/\">VXL Homepage</a>.
The source for VXL can be downloaded from
<a href=\"http://sourceforge.net/projects/vxl\">
  sourceforge.net/projects/vxl
</a>
<br />
<hr />
<h2>Search this Documentation Tree - using Google Site Search</h2>
<form method=\"get\" action=\"http://www.google.com/search\">
  <input type=\"text\"
         name=\"q\" size=\"31\" maxlength=\"255\" value=\"\" />
  <input type=\"submit\" value=\"Google Search\" /><br />
  <input type=\"radio\" name=\"sitesearch\" value=\"\" />
    The Web<br />
  <input type=\"radio\" name=\"sitesearch\"
         value=\"paine.wiau.man.ac.uk/pub/doc_vxl/\" checked />
    Manchester VXL Documentation<br />
  <input type=\"radio\" name=\"sitesearch\"
         value=\"public.kitware.com/vxl/doc/\">
    Kitware VXL Documentation<br />
  <input type=\"radio\" name=\"sitesearch\"
         value=\"lems.brown.edu/vision/vxl_doc/\">
    Brown VXL Documentation<br />
</form>
<br />
<hr />
Index generated by <em>config/cmake/doxygen/doxygen_makeall.cmake</em>
on ${date}.
<hr />
</body>
</html>"
    )
  set(${_index_html} "${index_html}" PARENT_SCOPE)
endfunction()

#---------------------------------------------------------------------
# Initial configuration.
#---------------------------------------------------------------------
# All the variables used in this script must be loaded from here.
include("${CMAKE_BINARY_DIR}/doxygen_configuration.cmake" OPTIONAL)

# Read in last revision built.
include("${CMAKE_BINARY_DIR}/doxygen_last_build_rev.cmake" OPTIONAL)

find_package(Subversion QUIET)

# Reset the file for new values.
file(WRITE "${CMAKE_BINARY_DIR}/doxygen_last_build_rev.cmake"
  "# *** This is a auto-generated file. DO NOT edit! ***\n\n"
  )

#---------------------------------------------------------------------
# Process each book.
#---------------------------------------------------------------------
foreach(book ${DOXYGEN_BOOK_LIST})
  string(REPLACE / _ bname ${book})

  doxygen_module_has_changed(${book}/doc/book ${bname}_book changed)
  if(changed)
    message(STATUS "Texi2html: ${book} being processed.")

    set(book_source_dir "${DOXYGEN_SOURCE_DIR}/${book}/doc/book")
    set(book_output_dir "${DOXYGEN_OUTPUT_DIR}/html/books/${book}")

    file(GLOB image_list "${book_source_dir}/*.eps")
    foreach(image ${image_list})
      get_filename_component(output_image ${image} NAME_WE)

      # copy if acceptable format is in source
      set(image_copied FALSE)
      foreach(ext png jpg jpeg)
        if(EXISTS "${book_source_dir}/${output_image}.${ext}")
          configure_file(
            "${book_source_dir}/${output_image}.${ext}"
            "${book_output_dir}/${output_image}.${ext}"
            COPYONLY
            )
          set(image_copied TRUE)
          break()
        endif()
      endforeach()

      # convert eps image to png
      if(NOT image_copied)
        if(NetPBM_FOUND)
          execute_process(
            COMMAND ${PSTOPNM_EXECUTABLE} -portrait -stdout ${image}
            COMMAND ${PNMTOPNG_EXECUTABLE}
            OUTPUT_FILE "${book_output_dir}/${output_image}.png"
            )
        elseif(ImageMagick_FOUND)
          execute_process(
            COMMAND ${ImageMagick_convert_EXECUTABLE}
              "${image}" "${output_image}.png"
            WORKING_DIRECTORY "${book_output_dir}"
            )
        endif()
      endif()
    endforeach()

    # copy texi files; else texi2html uses absolute paths for images
    file(GLOB texifile_list RELATIVE "${book_source_dir}"
      "${book_source_dir}/*.texi"
      )
    foreach(texifile ${texifile_list})
      configure_file(
        "${book_source_dir}/${texifile}"
        "${book_output_dir}/${texifile}"
        COPYONLY
        )
    endforeach()

    execute_process(
      COMMAND ${TEXI2HTML_EXECUTABLE}
        -split=chapter -l2h -number -output=. -I=. book.texi
      WORKING_DIRECTORY "${book_output_dir}"
      OUTPUT_FILE
        "${CMAKE_BINARY_DIR}/doxy/output/texi2html_${bname}.out"
      ERROR_FILE
        "${CMAKE_BINARY_DIR}/doxy/output/texi2html_${bname}.out"
      )
  else()
    message(STATUS "Texi2html: ${book} previously processed.")
  endif()
endforeach()

#---------------------------------------------------------------------
# Process each library.
#---------------------------------------------------------------------
file(MAKE_DIRECTORY "${DOXYGEN_OUTPUT_DIR}/tags")
foreach(library ${DOXYGEN_LIBRARY_LIST})
  string(REPLACE / _ libname ${library})

  doxygen_module_has_changed(${library} ${libname} changed)
  if(changed)
    message(STATUS "Doxygen: ${library} being processed.")

    # generate dep list
    set(prev_result 0)
    list(REMOVE_DUPLICATES DOXYGEN_${libname}_DEPS)
    list(LENGTH DOXYGEN_${libname}_DEPS result)
    while(NOT result EQUAL prev_result)
      set(prev_result ${result})
      foreach(dep ${DOXYGEN_${libname}_DEPS})
        string(REPLACE / _ depname ${dep})
        if(DOXYGEN_${depname}_DEPS)
          list(APPEND DOXYGEN_${libname}_DEPS ${DOXYGEN_${depname}_DEPS})
        endif()
      endforeach()
      list(REMOVE_DUPLICATES DOXYGEN_${libname}_DEPS)
      list(LENGTH DOXYGEN_${libname}_DEPS result)
    endwhile()

    # Work out how to get from current library to base
    # (e.g., "dir1" -> "..", "dir1/dir2" -> "../..", etc).
    string(REGEX REPLACE "[^/]+" .. relpath ${library})

    # set tagfiles for configuring @tagfiles@ entry in doxyfile
    set(tagfiles)
    foreach(dep ${DOXYGEN_${libname}_DEPS})
      string(REPLACE / _ depname ${dep})
      set(tagfiles
        "${tagfiles} \\\n \"${DOXYGEN_OUTPUT_DIR}/tags/${depname}.tag")
      set(tagfiles
        "${tagfiles} \\\n = ${relpath}/../${dep}/html\"")
    endforeach()

    # configure @tagfiles@ entry
    configure_file(
      "${CMAKE_BINARY_DIR}/doxy/output/doxyfile.${libname}"
      "${CMAKE_BINARY_DIR}/doxy/output/doxyfile.${libname}"
      )

    file(MAKE_DIRECTORY "${DOXYGEN_OUTPUT_DIR}/html/${library}/html")
    execute_process(
      COMMAND
        ${DOXYGEN_EXECUTABLE}
        "${CMAKE_BINARY_DIR}/doxy/output/doxyfile.${libname}"
      WORKING_DIRECTORY "${DOXYGEN_SOURCE_DIR}"
      OUTPUT_FILE
        "${CMAKE_BINARY_DIR}/doxy/output/${libname}.doxy_out"
      ERROR_FILE
        "${CMAKE_BINARY_DIR}/doxy/output/${libname}.doxy_out"
      )
  else()
    message(STATUS "Doxygen: ${library} previously processed.")
  endif()
endforeach()

#---------------------------------------------------------------------
# Build global index.
#---------------------------------------------------------------------
message(STATUS
  "Doxygen: generating index at "
  "${DOXYGEN_OUTPUT_DIR}/html/${DOXYGEN_INDEX_FILE}."
  )

if(DOXYGEN_MERGE_DOCS_WITH)
  set(external_books_tag "@external_books@")
  set(external_libraries_tag "@external_libraries@")
  set(external_books "-->")
  _print_book_links(external_books)
  set(external_books "${external_books}
<!-- @external_books_tag@ "
    )

  set(external_libraries "-->")
  _print_library_links(external_libraries)
  set(external_libraries "${external_libraries}
<!-- @external_libraries_tag@ "
    )

  file(READ "${DOXYGEN_OUTPUT_DIR}/html/${DOXYGEN_MERGE_DOCS_WITH}"
    index_html
    )
  string(CONFIGURE "${index_html}" index_html)
else()
  _print_header(index_html)
  set(index_html "${index_html}
<h2>Overview Documentation</h2>
<a href=\"https://vxl.github.io\">VXL Homepage</a>
<br />
<br />
<p>
  Overviews are compiled from the doc/book directory of each package.
</p>"
    )
  _print_book_links(index_html)
  set(index_html "${index_html}
<!-- @external_books@ -->
<br />
<hr />
<h2>Library Documentation</h2>"
    )
  _print_library_links(index_html)
  set(index_html "${index_html}
<!-- @external_libraries@ -->
<br />
<hr />"
    )
  _print_footer(index_html)
endif()

file(WRITE "${DOXYGEN_OUTPUT_DIR}/html/${DOXYGEN_INDEX_FILE}"
  "${index_html}"
  )
